<script setup lang="ts">
import API from '@/services';
import { Message } from '@arco-design/web-vue';
import { IconInfoCircle } from '@arco-design/web-vue/es/icon';
import { onMounted, reactive, ref, watch } from 'vue';
import LeftJoinForm from '../LeftJoinForm/index.vue';

const emit = defineEmits(['success']);
interface ListValueI {
  tableId: undefined | number;
  joinTableId: undefined | number;
  tableField: undefined | number;
  joinTableField: undefined | number;
}
const defaultFormData: {
  modelName: string;
  modelDesc: string;
  tableId: number | undefined;
  list: Array<{ value: ListValueI }>;
} = {
  modelName: '',
  modelDesc: '',
  tableId: undefined,
  list: [
    {
      value: {
        tableId: undefined,
        joinTableId: undefined,
        tableField: undefined,
        joinTableField: undefined
      }
    }
  ]
};
const formData = reactive({
  ...defaultFormData,
  list: defaultFormData.list.concat([])
});
const handleSubmit = ({ values, errors }: any) => {};
interface OptionsI {
  label: string;
  value: string | number | undefined;
  tableName: string;
}
const tableOptions = ref<OptionsI[]>([]);
// 定义事实表类型( 1:全量 2:增量 3:拉链)
const TableType = ['全量表', '增量表', '拉链表'];
const getTableData = async () => {
  try {
    const res = await API.dataTable.postDataTableGetTableList({ tableType: 1 });
    tableOptions.value =
      res?.data?.map((d: any) => {
        let labelStr =
          d && d.updateType
            ? `${d.tableName}(${TableType[Number(d.updateType) - 1]})`
            : `${d.tableName}`;
        return {
          label: labelStr,
          tableName: d.tableName || '',
          value: d.id
        };
      }) || [];
  } catch (error) {}
};
const dimTableOptions = ref<OptionsI[]>([]);
const getDimTableData = async () => {
  try {
    const res = await API.dataTable.postDataTableGetTableList({ tableType: 2 });
    dimTableOptions.value =
      res?.data?.map((d) => {
        return {
          label: `${d.tableName}`,
          tableName: d.tableName || '',
          value: d.id
        };
      }) || [];
  } catch (error) {}
};
onMounted(() => {
  getTableData();
  getDimTableData();
});
const tableLeftOptions = ref<any[]>([]);
const getTableOption = (options: any[], value: string | number | undefined) => {
  if (!value) {
    return {};
  }
  const item = options.find((option) => option.value === value) || {};
  return item;
};
watch(
  () => formData.tableId,
  () => {
    formData.list = [
      {
        value: {
          tableId: formData.tableId,
          joinTableId: undefined,
          tableField: undefined,
          joinTableField: undefined
        }
      }
    ];
    const item = getTableOption(tableOptions.value, formData.tableId);
    tableLeftOptions.value = [item].concat(dimTableOptions.value);
  }
);
const onAddList = () => {
  formData.list.push({
    value: {
      tableId: undefined,
      joinTableId: undefined,
      tableField: undefined,
      joinTableField: undefined
    }
  });
};
const onRemoveList = (index: number) => {
  formData.list.splice(index, 1);
};
const formRef = ref();
const onBeforeOkAsync = async () => {
  const err = await formRef.value.validate();
  if (!err) {
    try {
      const list = formData.list.map((val) => {
        const tableData = getTableOption(
          tableLeftOptions.value,
          val.value.tableId
        );
        const joinTableData = getTableOption(
          dimTableOptions.value,
          val.value.joinTableId
        );
        return {
          ...val.value,
          tableName: tableData.tableName,
          joinTableName: joinTableData.tableName
        };
      });
      const tableD = getTableOption(tableOptions.value, formData.tableId);
      const res = await API.dataModel.postSaveModel({
        modelName: formData.modelName,
        modelDesc: formData.modelDesc,
        tableId: Number(formData.tableId),
        tableName: tableD.tableName,
        // @ts-ignore
        list
      });
      if (res.code !== 200) {
        throw new Error('接口错误');
      }
      return true;
    } catch (error) {
      throw error;
    }
  }
  {
    throw new Error('校验错误');
  }
};
const onBeforeOk = (done: any) => {
  onBeforeOkAsync()
    .then(() => {
      Message.success('创建模型成功');
      emit('success');
      done(true);
      onDrawerClose();
    })
    .catch((e) => {
      done(false);
    });
};

const onDrawerClose = () => {
  Object.keys(defaultFormData).forEach((key) => {
    formData[key] = defaultFormData[key];
  });
};
</script>
<template>
  <a-drawer
    unmountOnClose
    :width="684"
    @before-ok="onBeforeOk"
    @close="
      () => {
        onDrawerClose();
      }
    "
  >
    <template #title
      ><span style="font-weight: bold">创建指标模型</span></template
    >
    <a-form
      ref="formRef"
      :model="formData"
      auto-label-width
      @submit="handleSubmit"
    >
      <div class="title">基本信息</div>
      <a-form-item
        show-colon
        required
        label="模型名称"
        field="modelName"
        :rules="[{ required: true, message: '请输入模型名称' }]"
      >
        <a-input v-model="formData.modelName" />
      </a-form-item>
      <a-form-item show-colon label="模型描述" field="modelDesc">
        <a-input v-model="formData.modelDesc" />
      </a-form-item>
      <div class="title">模型结构配置</div>
      <a-form-item
        show-colon
        required
        label="事实表"
        field="tableId"
        :rules="[{ required: true, message: '请选择事实表' }]"
      >
        <a-select v-model="formData.tableId" :options="tableOptions" />
      </a-form-item>
      <a-form-item show-colon required label="事实表关联">
        <a-tooltip content="必须为事实表关联维表，也可追加维表与维表的关联。">
          <icon-info-circle :strokeWidth="1" />
        </a-tooltip>
      </a-form-item>
      <div>
        <LeftJoinForm
          v-for="(post, index) of formData.list"
          v-model="post.value"
          :key="index"
          :disable-remove="index === 0"
          :tableDisabled="index === 0"
          :fieldPath="`list.${index}.value`"
          :tableLeftOptions="tableLeftOptions"
          :table-right-options="dimTableOptions"
          @remove="() => onRemoveList(index)"
        />
      </div>
      <a-button @click="onAddList" type="outline" style="width: 80px"
        >+添加</a-button
      >
    </a-form>
  </a-drawer>
</template>

<style lang="scss" scoped>
.title {
  color: #33353b;
  font-weight: 600;
}
</style>
